package com.jan.server;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

import net.sf.json.JSONObject;

public class ClientConnecttionThread
    implements Runnable
{
  private Socket socket;
  public ClientConnecttionThread(Socket socket){
    this.socket=socket;
  }

  @Override
  public void run()
  {
    try
    {
      InputStream in=socket.getInputStream();
      OutputStream out=socket.getOutputStream();
      byte[] bs=new byte[1024];
      while(true){
        if(in.available()>0){
          int length=in.read(bs);
          String s=new String(bs, 0, length);
          JSONObject json=JSONObject.fromObject(s);
          System.out.println(s);
          DataPacket packet=new DataPacket(json.getString("sender"),json.getString("reciver"),json.getString("msg"));
          if(packet.getReciver().equals("10000")){
            TcpServer.addClient(packet.getSender(), this);
          }else{
            ClientConnecttionThread conn=TcpServer.getClient(packet.getReciver());
            if(conn!=null){
              OutputStream out2=conn.getSocket().getOutputStream();
              out2.write(packet.toStringPacket().getBytes());
            }else{
              DataPacket packet2=new DataPacket("10000",packet.getReciver(),"the user is not online");
              out.write(packet2.toStringPacket().getBytes());
            }
          }
        }
      }
    }
    catch (IOException e)
    {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

  }

  public Socket getSocket()
  {
    return socket;
  }

  public void setSocket(Socket socket)
  {
    this.socket = socket;
  }

}
